﻿using Ace.Application;
using Ace.Data;
using Ace.Entity.Wiki;
using Ace.Exceptions;
using Ace.IdStrategy;
using Chloe;
using Chloe.MySql;
using Chloe.SqlServer;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Ace.Application.Wiki
{
    public interface IPromotionItemService : IAppService
    {
        List<PromotionItem> GetList(string PromotionId);

        List<PromotionItemInfo> GetListInfo(string PromotionId);


        void Add(PromotionItem input); 
        void Delete(string PromotionId, string ProductID);
        
        PagedData<PromotionItem> GetPageData(Pagination page, string PromotionId);
    }

    public class PromotionItemService : AppServiceBase<PromotionItem>, IPromotionItemService
    {
        public PromotionItemService(IDbContext dbContext, IServiceProvider services) : base(dbContext, services)
        {
        }

        public List<PromotionItem> GetList(string PromotionId)
        {
            var q = this.Query;
            if (PromotionId.IsNotNullOrEmpty())
            {
                q = q.Where(a => a.PromotionId== PromotionId);
            }
            var ret = q.ToList();
            return ret;
        }

        public List<PromotionItemInfo> GetListInfo(string PromotionId)
        {
            string sql = "select a.PromotionId,a.ProductID,b.ProductName from promotion_item a left join product b on a.ProductID=b.Id where a.PromotionId=?PromotionId ";
            List<PromotionItemInfo> list = this.DbContext.SqlQuery<PromotionItemInfo>(sql, new { PromotionId = PromotionId }).ToList();
            return list;
        }

        public  int  Count(string ProductID)
        {
            int c =this.DbContext.Query<PromotionItem>().Where(a => a.ProductID == ProductID).Count();
            return c;
        }
         
        public void Add(PromotionItem input)
        {
            //this.InsertFromDto(input);
            int c = Count(input.ProductID);
            if(c==0)
            {
                this.DbContext.Insert(input);
            }
            
        }
        
 

        public void Delete(string PromotionId,string ProductID)
        {
            this.DbContext.Delete<PromotionItem>(a => a.PromotionId == PromotionId&& a.ProductID== ProductID);
        }


        public PagedData<PromotionItem> GetPageData(Pagination page, string PromotionId)
        {
            var q = this.DbContext.Query<PromotionItem>();
            if(!string.IsNullOrEmpty(PromotionId))
            {
                q = q.Where(a => a.PromotionId == PromotionId);
            }
            
            PagedData<PromotionItem> pagedData = q.TakePageData(page);
            
            return pagedData;
        }

         



    }

}
